#include "head.h"

int tcp(int* fd)
{
    char ip[20] = {0};
    char port[10] = {0};
    getparameter("ip", ip);
    getparameter("port", port);

    int sock_fd = socket(AF_INET, SOCK_STREAM, 0);


    int reuse = 1;
    setsockopt(sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));

    struct sockaddr_in addr;
    addr.sin_addr.s_addr = inet_addr(ip);
    addr.sin_port = htons(atoi(port));
    addr.sin_family = AF_INET;
    if(bind(sock_fd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
        error(1, errno, "bind");

    if(listen(sock_fd, LISTEN_LINK) == -1)
        error(1, errno, "listen");

    *fd = sock_fd;
    return 0;
}

// 增加新连接
int new_link(int current_fd, int epoll_fd, int fd, time_queue_t* time_queue, time_hash_t* hash)
{   
    printf("新连接来了\n");
    int sock_fd = accept(fd, NULL, NULL);
    epoll_add(epoll_fd, sock_fd);

    // 加入时间队列和hash表
    time_t t = time(NULL);
    insert_time_queue(time_queue, sock_fd, t);
    insert_time_hash(hash, sock_fd, t);
    return 0;
}